package com.yao.system.controller;


import com.yao.system.annotation.MyAnnotation;
import com.yao.system.entity.Result;
import com.yao.system.OSS.AliOSSUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/common")
@Slf4j
public class commonController {

    @Value("${rat.path}")
    private String basePath;

    /**
     * 上传图片
     * @param file
     * @return
     * @throws IOException
     */
    @MyAnnotation
    @PostMapping("/upload")
    public Result upload(@RequestPart("file") MultipartFile file) throws IOException {
        log.info("文件上传:{}", file.toString());

        String fileURL = AliOSSUtil.upload(file);
        return Result.ok(fileURL,"上传成功");
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
